<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="科室" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入科室"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="接诊类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择接诊类型" clearable style="width: 200px;">
          <el-option
            v-for="dict in doctor_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="医生" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="患者" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="就诊状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择就诊状态" clearable style="width: 200px;">
          <el-option
            v-for="dict in fy_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['work:work:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['work:work:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['work:work:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['work:work:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="patient-cards">
      <div v-loading="loading" class="card-list">
        <div class="card-row">
          <div v-for="(item, index) in workList" :key="index" class="patient-card">
            <div class="card-content">
              <div class="patient-main-info">
                <div class="status-tag">
                  <dict-tag :options="fy_status" :value="item.state"/>
                </div>
                <div class="name-row">
                  <span class="patient-name">
                    <span v-for="p in patientList" :key="p">
                      <template v-if="item.patientId == p.id">
                        {{ p.name }}  {{ p.sex == '1' ? '男' : '女' }} {{ p.age }}
                      </template>
                    </span>
                  </span>
                  <!-- <el-tag v-if="item.type === '1'" type="warning" size="small" class="vip-tag">VIP3</el-tag>
                  <span class="gender-age">{{ item.sex == '1' ? '男' : '女' }} {{ item.age }}</span> -->
                </div>
                <div class="create-time">创建时间：{{ parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
                <div class="dept-doctor">
                  <span>科室：</span>
                  <span v-for="d in deptList" :key="d">
                    <span v-if="item.deptId == d.deptId">{{ d.deptName }}</span>
                  </span>
                  <span class="divider">|</span>
                  <span>医生：</span>
                  <span v-for="u in userList" :key="u">
                    <span v-if="item.doctorId == u.userId">{{ u.userName }}</span>
                  </span>
                </div>
                <div class="phone">手机号码：{{ item.phone || '18879867899' }}</div>
              </div>
              <div class="action-buttons">
                <div class="button-group">
                  <el-button 
                    v-if="Number(item.state) === 2"
                    type="primary" 
                    link 
                    class="visit-btn"
                    @click="handleDiagnosis(item)">就诊</el-button>
                  <el-button 
                    v-else-if="Number(item.state) === 3"
                    type="info" 
                    link 
                    class="visit-btn"
                    disabled>就诊中</el-button>
                  <el-button 
                    v-else
                    type="success" 
                    link 
                    class="visit-btn"
                    disabled>已就诊</el-button>
                  <el-button 
                    type="primary" 
                    link 
                    class="info-btn" 
                    @click="toInfo(item)">查看患者信息</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作台接诊对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="workRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科室id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入科室id" />
        </el-form-item>
        <el-form-item label="接诊类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择接诊类型">
            <el-option
              v-for="dict in doctor_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生id" prop="doctorId">
          <el-input v-model="form.doctorId" placeholder="请输入医生id" />
        </el-form-item>
        <el-form-item label="患者id" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者id" />
        </el-form-item>
        <el-form-item label="就诊状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择就诊状态">
            <el-option
              v-for="dict in fy_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Work">
import { listWork, getWork, delWork, addWork, updateWork } from "@/api/work/work";
import { listDept } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { listPatient } from "@/api/work/work";
import { useRouter } from 'vue-router'
const router = useRouter()


const { proxy } = getCurrentInstance();
const { doctor_type, fy_status } = proxy.useDict('doctor_type', 'fy_status');

const workList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptList = ref([]);
const userList = ref([]);
const patientList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    type: null,
    doctorId: null,
    createTime: null,
    patientId: null,
    state: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询工作台接诊列表 */
function getList() {
  loading.value = true;
  listWork(queryParams.value).then(response => {
    workList.value = response.rows;
    // console.log(workList.value);
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询部门列表 */
// function getDeptList() {
//   loading.value = true;
//   listDept(queryParams.value).then(response => {
//     deptList.value = response.data;
//     console.log(deptList.value);
//     loading.value = false;
//   });
//   console.log(deptList.value);
// }
async function getDeptList() {
  try {
    loading.value = true;
    const response = await listDept(); // 等待异步操作完成
    deptList.value = response.data;
    
  } catch (error) {
    console.error('Error fetching department list:', error);
  } finally {
    loading.value = false;
  }
  // console.log(deptList.value); // 数据加载完成后打印
}

/** 查询用户列表 */
// function getUserList() {
//   loading.value = true;
//   listUser().then(res => {
//     loading.value = false;
//     userList.value = res.rows;
//     total.value = res.total;
//   });
//   console.log(userList.value);
// };

async function getUserList() {
  try {
    loading.value = true;

    // 调用异步方法并等待结果
    const res = await listUser();

    // 更新数据
    userList.value = res.rows;

    // 打印更新后的 userList 数据
    // console.log(userList.value);
  } catch (error) {
    console.error('Error fetching user list:', error);
  } finally {
    // 确保加载状态被重置
    loading.value = false;
  }
}

/** 查询患者信息列表 */
// function getList() {
//   loading.value = true;
//   listPatient().then(response => {
//     patientList.value = response.rows;
//     loading.value = false;
//   });
// }
//查询全部患者信息
async function getPatientList() {
  try {
    loading.value = true;

    // 调用异步方法并等待结果
    const response = await listPatient();
    // console.log(response);
    // 更新数据
    patientList.value = response.data;
  } catch (error) {
    console.error('Error fetching patient list:', error);
  } finally {
    // 确保加载状态被重置
    loading.value = false;
  }
  // console.log(patientList.value);
}

/* 处理就诊按钮点击 */
function handleDiagnosis(row) {
  if (Number(row.state) !== 2) {
    return;
  }
  const sendInfo = {
    id: row.id,
    patientId: row.patientId,
    doctorId: row.doctorId, 
  } 
  router.push({
    path: '/work/diagnosis',
    query: {
      data: JSON.stringify(sendInfo)
    }
  });
}

/* 跳转界面去查看患者信息 */
function toInfo(row) {
  // console.log(row);  
  const sendInfo = {
    //挂号单号
    id: row.id,
    //患者id
    patientId: row.patientId,
    //医生id
    doctorId: row.doctorId, 
  }
  router.push({
    path: 'patientInfo', // 确保路径是绝对路径
    query: {
      data: JSON.stringify(sendInfo)
    } 
  })  
}




// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    type: null,
    doctorId: null,
    money: null,
    createTime: null,
    createPeople: null,
    patientId: null,
    state: null
  };
  proxy.resetForm("workRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加工作台接诊";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWork(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改工作台接诊";
  });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["workRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWork(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWork(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除工作台接诊编号为"' + _ids + '"的数据项？').then(function() {
    return delWork(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('work/work/export', {
    ...queryParams.value
  }, `work_${new Date().getTime()}.xlsx`)
}

getList();
getDeptList();
getUserList();
getPatientList();
</script>

<style scoped>
.patient-cards {
  margin-top: 20px;
  padding: 0 10px;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.patient-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  padding: 16px;
  position: relative;
}

.patient-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.status-tag {
  position: absolute;
  top: 16px;
  right: 16px;
}

.patient-main-info {
  padding-top: 24px;
}

.name-row {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-right: 12px;
}

.vip-tag {
  font-size: 12px;
  margin: 0 12px;
}

.gender-age {
  color: #666;
  font-size: 14px;
  margin-left: 8px;
}

.create-time, .dept-doctor, .phone {
  color: #666;
  font-size: 14px;
}

.dept-doctor .divider {
  margin: 0 8px;
  color: #dcdfe6;
}

.action-buttons {
  margin-top: 12px;
  border-top: 1px solid #ebeef5;
  padding-top: 12px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.visit-btn {
  min-width: 60px;
}

.visit-btn.visiting {
  color: #909399 !important;
  cursor: not-allowed;
}

.visit-btn.completed {
  color: #67c23a !important;
  cursor: not-allowed;
}

.info-btn {
  color: #409EFF;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
